package main

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

type Session struct {
	AccessToken   string `json:"access_token"`
	RefreshToken  string `json:"refresh_token"`
	SessionKey    string `json:"session_key"`
	SessionSecret string `json:"session_secret"`
	Scope         string `json:"scope"`
	ExpiresIn     int    `json:"expires_in"`
}

type Result struct {
	LogId     int64       `json:"log_id"`
	Direction int         `json:"direction"`
	Wrn       int         `json:"words_result_num"`
	Wr        WordsResult `json:"words_result"`
}

type Words struct {
	Words string `json:"words"`
}

const (
	clientID     = "OSuWrAYNnfKYDW3VmFwB3Zfs"         // API Key
	clientSecret = "jQs5WjGgVEiTOHdXVtx19YaTaynqCgg8" // Secret Key
)

//func XXX() {
//	res, err := NewBaiduOcrClient("lims", clientID, clientSecret)
//    if err != nil {
//		fmt.Println(err)
//		return;
//	}
//
//	img, err := ioutil.ReadFile("code.png")
//	if err != nil {
//		fmt.Println("ioutil.ReadFile()", err)
//		return
//	}
//	re1, err := res.OcrPic(img)
//	if err != nil{
//		fmt.Println(err)
//		return;
//	}
//	fmt.Println(re1.shareBinary)
//}

func main() {
	token, err := accessToken(clientID, clientSecret)
	if err != nil {
		fmt.Println("accessToken()", err)
		return
	}
	fmt.Println("Token:", *token)

	img, err := ioutil.ReadFile("code3.png")
	if err != nil {
		fmt.Println("ioutil.ReadFile()", err)
		return
	}
	err, str := ImageToText(*token, img)
	if err != nil {
		fmt.Println("ImageToText()", err)
		return
	}
	fmt.Println(str)

}

func accessToken(id string, secret string) (token *string, err error) {
	apiURL := fmt.Sprintf("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s", id, secret)
	resp, err := http.Get(apiURL)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	var session Session
	err = json.Unmarshal(body, &session)
	if err != nil {
		return nil, err
	}
	token = &session.AccessToken
	return token, nil
}

func ImageToText(token string, image []byte) (error, string) {
	apiURL := fmt.Sprintf("https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token=%s", token)
	param := "image=" + url.QueryEscape(base64.StdEncoding.EncodeToString(image))
	resp, err := http.Post(apiURL, "application/x-www-form-urlencoded", strings.NewReader(param))
	if err != nil {
		return err, ""
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err, ""
	}
	return nil, string(body)
}
